import Konva from "konva"
import { componentsShapeType } from '../utills/consts'

/**
 * KonvaJs核心类 - 提供基本画布功能
 * 只包含核心功能，复杂逻辑应在页面组件中实现
 */
export class KonvaJs {
    constructor(id, id2) {
        // 基础属性
        this.id = id;            // 画布容器ID
        this.id2 = id2;          // 外部容器ID
        this.boardCount = 0;     // 画板数量
        this.currentBoardIndex = 0; // 当前活动画板索引
        this.initialStageHeight = 0; // 初始舞台高度
        
        // Konva基础对象
        this.stage = null;       // 舞台
        this.layer = this.newLayer(); // 图层
        this.tr = this.newTransformer(); // 变换器
        this.group = this.newGroup({ x: 0, y: 0 }); // 主组
        
        // 画板相关
        this.boards = [];        // 画板数组
        this.onBoardChange = null; // 画板切换回调
        this.onContentChange = null; // 内容变化回调
    }

    /**
     * 初始化画布
     */
    init() {
        const el = document.getElementById(this.id2);
        if (!el) return;

        // 设置舞台
        const { clientWidth, clientHeight } = el;
        this.initialStageHeight = clientHeight;
        this.stage = this.newStage({
            container: this.id,
            width: clientWidth,
            height: clientHeight,
            draggable: false,
            type: componentsShapeType.CANVAS,
        });

        // 添加图层和组件
        this.layer.add(this.group);
        this.layer.add(this.tr);
        this.stage.add(this.layer);
        
        // 初始化第一个画板
        this.drawBoard();
        
        // 添加事件监听器
        this.addScrollListener();
        this.setupStageClickListener();
        
        // 添加变换器的变换结束事件监听
        this.tr.on('transformend', () => {
            if (this.onContentChange) {
                this.onContentChange();
            }
        });
    }

    /**
     * 绘制画板
     */
    drawBoard() {
        if (!this.stage) return;

        const width = 700;
        const height = 700;

        // 计算位置
        const x = this.stage.width() / 2 - width / 2;
        let y, sectionStart = 0;
        
        if (this.boardCount === 0) {
            // 第一个画板居中
            y = this.stage.height() / 2 - height / 2;
        } else {
            // 新画板位置
            this.boardCount++;
            const newStageHeight = this.initialStageHeight * this.boardCount;
            this.stage.height(newStageHeight);
            
            sectionStart = this.initialStageHeight * (this.boardCount - 1);
            y = sectionStart + (this.initialStageHeight / 2) - (height / 2);
        }

        // 创建画板和图形容器
        const board = this.newRect({
            x, y, width, height,
            fill: '#ffffff',
            stroke: '#ddd',
            strokeWidth: 2
        });
        
        const boardIndex = this.boardCount;
        const boardShapesGroup = this.newGroup({
            x, y,
            name: `board-${boardIndex}-shapes-container`
        });

        // 添加到画布
        this.group.add(board);
        this.layer.add(boardShapesGroup);
        
        // 保存画板信息
        this.boards.push({
            board,
            position: y,
            sectionStart,
            shapesGroup: boardShapesGroup
        });

        // 更新画板计数和当前画板
        if (this.boardCount === 0) {
            this.boardCount = 1;
            this.currentBoardIndex = 0;
        } else {
            this.currentBoardIndex = this.boardCount - 1;
            this.scrollToNewBoard(sectionStart);
        }
        
        // 通知更新
        if (this.onBoardChange) {
            this.onBoardChange(this.currentBoardIndex);
        }
        
        // 触发内容变化回调
        if (this.onContentChange) {
            this.onContentChange();
        }

        this.layer.batchDraw();
    }

    /**
     * 添加滚动监听，检测当前可见的画板
     */
    addScrollListener() {
        const container = document.getElementById(this.id2);
        if (!container) return;

        container.addEventListener('scroll', () => {
            const scrollTop = container.scrollTop;

            for (let i = 0; i < this.boards.length; i++) {
                const sectionStart = i === 0 ? 0 : this.initialStageHeight * i;
                const sectionEnd = this.initialStageHeight * (i + 1);

                if (scrollTop >= sectionStart && scrollTop < sectionEnd) {
                    if (this.currentBoardIndex !== i) {
                        this.currentBoardIndex = i;
                        if (this.onBoardChange) {
                            this.onBoardChange(i);
                        }
                    }
                    break;
                }
            }
        });
    }

    /**
     * 跳转到指定画板
     * @param {number} index 画板索引
     */
    jumpToBoard(index) {
        if (index < 0 || index >= this.boards.length) return;

        const boardInfo = this.boards[index];
        this.scrollToNewBoard(boardInfo.sectionStart);

        this.currentBoardIndex = index;
        if (this.onBoardChange) {
            this.onBoardChange(this.currentBoardIndex);
        }
    }

    /**
     * 滚动到画板位置
     * @param {number} yPosition 纵向位置
     */
    scrollToNewBoard(yPosition) {
        const centerContainer = document.getElementById(this.id2);
        if (!centerContainer) return;
        
        setTimeout(() => {
            centerContainer.scrollTo({
                top: yPosition,
                behavior: 'smooth'
            });
        }, 100);
    }

    isPointInBoard(x, y, boardX, boardY, width, height) {
        return x >= boardX && x <= boardX + width && 
               y >= boardY && y <= boardY + height;
    }

    /**
     * 获取当前活动的画板和图形容器
     * @returns {Object|null} 当前画板信息或null
     */
    getCurrentBoard() {
        if (!this.stage || this.boards.length === 0) return null;
        return this.boards[this.currentBoardIndex];
    }

    /**
     * 根据容器名查找容器
     * @param {string} containerName 容器名称
     * @returns {Konva.Group|null} 找到的容器或null
     */
    findContainer(containerName) {
        let container = null;
        this.boards.forEach(board => {
            if (board.shapesGroup.name() === containerName) {
                container = board.shapesGroup;
            }
        });
        return container;
    }

    /**
     * 获取随机颜色
     * @returns {string} 颜色代码
     */
    getRandomColor() {
        const colors = [
            '#FF5252', '#FF4081', '#E040FB', '#7C4DFF',
            '#536DFE', '#448AFF', '#40C4FF', '#18FFFF',
            '#64FFDA', '#69F0AE', '#B2FF59', '#EEFF41',
            '#FFFF00', '#FFD740', '#FFAB40', '#FF6E40'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    /**
     * 确保舞台点击监听
     */
    setupStageClickListener() {
        if (!this.stage.hasClickListener) {
            this.stage.on('click', (e) => {
                if (e.target === this.stage) {
                    this.tr.nodes([]);
                    this.layer.batchDraw();
                }
            });
            this.stage.hasClickListener = true;
        }
    }

    /**
     * 选中节点
     * @param {Konva.Node} node 要选中的节点
     */
    selectNode(node) {
        this.tr.nodes([]);
        this.tr.nodes([node]);
        this.layer.batchDraw();
    }

    /**
     * 清除选择
     */
    clearSelection() {
        this.tr.nodes([]);
        this.layer.batchDraw();
    }

    /**
     * 添加节点到指定图层
     * @param {Konva.Node} node 要添加的节点
     * @param {Konva.Group} container 容器
     */
    addNodeToContainer(node, container) {
        container.add(node);
        this.layer.batchDraw();
        
        // 触发内容变化回调
        if (this.onContentChange) {
            this.onContentChange();
        }
    }

    /**
     * 删除节点
     * @param {Konva.Node} node 要删除的节点
     */
    removeNode(node) {
        node.destroy();
        this.layer.batchDraw();
        
        // 触发内容变化回调
        if (this.onContentChange) {
            this.onContentChange();
        }
    }


    addShape(shapeType, x, y) {
        return this.createShape(shapeType, x, y);
    }

   
    createShape(shapeType, x, y) {
        if (!this.stage || this.boards.length === 0) return null;

        // 获取当前画板
        const currentBoard = this.getCurrentBoard();
        if (!currentBoard) return null;
        
        const board = currentBoard.board;
        const shapesGroup = currentBoard.shapesGroup;

        // 检查是否在画板范围内
        const boardX = board.x();
        const boardY = board.y();
        
        if (!this.isPointInBoard(x, y, boardX, boardY, board.width(), board.height())) {
            return null;
        }

        // 计算相对于画板的坐标
        const relativeX = x - boardX;
        const relativeY = y - boardY;
        
        // 创建图形
        const shape = this.createShapeByType(shapeType, relativeX, relativeY);
        if (!shape) return null;
        
        // 添加到画板
        this.addNodeToContainer(shape, shapesGroup);
        this.setupStageClickListener();
        
        return shape;
    }
    
  
    createShapeByType(shapeType, x, y) {
        const size = 50;
        const shapeId = 'shape-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
        const commonProps = {
            draggable: true,
            id: shapeId,
            stroke: '#333',
            strokeWidth: 1,
            fill: this.getRandomColor()
        };
        
        let shape = null;
        
        switch (shapeType) {
            case 'rectangle':
                shape = this.newRect({
                    ...commonProps,
                    x: x - size / 2,
                    y: y - size / 2,
                    width: size,
                    height: size
                });
                break;
                
            case 'circle':
                shape = this.newCircle({
                    ...commonProps,
                    x: x,
                    y: y,
                    radius: size / 2
                });
                break;
                
            case 'triangle':
                shape = this.newRegularPolygon({
                    ...commonProps,
                    x: x,
                    y: y,
                    sides: 3,
                    radius: size / 2
                });
                break;
                
            case 'star':
                shape = this.newStar({
                    ...commonProps,
                    x: x,
                    y: y,
                    numPoints: 5,
                    innerRadius: size / 4,
                    outerRadius: size / 2
                });
                break;
                
            case 'text':
                shape = this.newText({
                    x: x,
                    y: y,
                    text: '双击编辑文字',
                    fontSize: 18,
                    fontFamily: 'Arial',
                    fill: '#333',
                    padding: 5,
                    draggable: true,
                    id: shapeId
                });
                break;
        }
        
        if (shape) {
            // 添加点击选择事件
            shape.on('click', (e) => {
                e.cancelBubble = true;
                this.selectNode(shape);
            });
            
            // 添加拖动事件
            shape.on('dragstart', () => {
                shape.oldX = shape.x();
                shape.oldY = shape.y();
            });
            
            // 添加拖动结束事件，触发内容变化
            shape.on('dragend', () => {
                if (this.onContentChange) {
                    this.onContentChange();
                }
            });
            
            // 添加变换结束事件，触发内容变化
            shape.on('transformend', () => {
                if (this.onContentChange) {
                    this.onContentChange();
                }
            });
        }
        
        return shape;
    }

    // Konva基础对象创建方法
    newStage(data) { return new Konva.Stage(data); }
    newLayer(data) { return new Konva.Layer(data); }
    newTransformer(data) { return new Konva.Transformer(data); }
    newGroup(data) { return new Konva.Group(data); }
    newRect(data) { return new Konva.Rect(data); }
    newCircle(data) { return new Konva.Circle(data); }
    newText(data) { return new Konva.Text(data); }
    newStar(data) { return new Konva.Star(data); }
    newRegularPolygon(data) { return new Konva.RegularPolygon(data); }
    newLine(data) { return new Konva.Line(data); }
    newArrow(data) { return new Konva.Arrow(data); }
    newImage(data) { return new Konva.Image(data); }
}